<?php

namespace app\common\controller;

use app\common\library\Auth;
use app\admin\model\Apiconfig;

use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;

use think\Db;
use app\common\library\ApiToken;

/**
 * API控制器基类
 */
class Api
{

    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth 
     */
    protected $auth = null;
	
	// 开放接口序列号
	protected $openApiSn = [];
	
	// 接口配置
	//protected $apiConfig = null;
	
	// 参数调用数据对象
	protected $apiResponse = [];

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList)
        {
            foreach ($this->beforeActionList as $method => $options)
            {
                is_numeric($method) ?
                                $this->beforeAction($options) :
                                $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        $this->auth = Auth::instance();
		
		/* $this->apiConfig = new Apiconfig(); */
		
		$this->openApiSn = $this->getApiAllSno();
		
		if(empty($this->openApiSn)){
			$this->error('No Apis (500).');
		}

        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->request('token') ?: $this->request->cookie('token');

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin))
        {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin())
            {
                $this->error(__('Please login first'));
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight))
            {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path))
                {
                    $this->error(__('You have no permission'));
                }
            }
        }
        else
        {
            // 如果有传递token才验证是否登录状态
            if ($token)
            {
                $this->auth->init($token);
            }
        }
        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = '', $type = 'json', array $header = [])
    {
        $this->result($data, 1, $msg, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = '', $type = 'json', array $header = [])
    {
        $this->result($data, 0, $msg, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $data   要返回的数据
     * @param int    $code   返回的 code
     * @param mixed  $msg    提示信息
     * @param string $type   返回数据格式
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }

    /**
     * 未找到请求的接口
     */
    public function _empty()
    {
        return $this->error('Api not found');
    }

    /**
     * 前置操作
     * @access protected
     * @param  string $method  前置操作方法名
     * @param  array  $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only']))
        {
            if (is_string($options['only']))
            {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only']))
            {
                return;
            }
        }
        elseif (isset($options['except']))
        {
            if (is_string($options['except']))
            {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except']))
            {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @param  mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate))
        {
            $v = Loader::validate();
            $v->rule($validate);
        }
        else
        {
            // 支持场景
            if (strpos($validate, '.'))
            {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate)
            $v->batch(true);
        // 设置错误信息
        if (is_array($message))
            $v->message($message);
        // 使用回调验证
        if ($callback && is_callable($callback))
        {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data))
        {
            if ($this->failException)
            {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }
	
	// 获得接口所有的数据信息
	public function getApiAllSetting( $field = "*" )
	{		
		$result = Db::name("apiconfig")->where(['state' => '1'])->field($field)->select();
		return $result;		
	}
	
	// 获得 --所有接口序列号-- 的数据
	public function getApiAllSno()
	{
		$r = $this->getApiAllSetting('apisn');
		
		if(count($r)){
			
			$r = array_map('current', $r);
			return $r;
		} else {
			return [];
		}
	}
	
	// 根据接口序号，获得接口的配置信息
	public function getApiSetting( $apiSn = null, $field = '*' )
	{
		if(empty($apiSn)){
			return [];
		}
		
		$apiConf = Db::name("apiconfig")->where(['apisn' => $apiSn])->field($field)->find();
		
		return $apiConf;		
	}
	
	
	
	/**
     * 验证参数有效性
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @param  mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
	 public function doParameterCheck($apiSn = null){
		
		if(is_null($apiSn)) {
			$this->error("Empty ApiSn (500).");
		}
		
		if(!in_array($apiSn, $this->openApiSn)){
			$this->error("Api Unavailable");
		}
				 
		$checkTag = true; // 默认检查通过
		$checkData = []; // 获得的参数数据		
		$logData['ParameterCheck'] = []; //  日志数据
		switch($apiSn) {
			case 'SN1000': # 获得令牌
			{
				$checkData['instrument_sn'] = $this->request->get('instrument_sn','');
				$checkData['check'] = $this->request->get('check','');								
				
				if( empty($checkData['instrument_sn']) or empty($checkData['check']) or (32 != strlen($checkData['check'])) ){
					$checkTag = false;
					$logData['ParameterCheck']['Params']['error'] = 'Parameter Error.';					
					break;
				}			
				
				$part4_9 = substr($checkData['check'],3,6);
				$part12_27 = substr($checkData['check'],11,16);
				$logData['ParameterCheck']['Hash'] = [
					'part4-9' => $part4_9,
					'part12-27' => $part12_27 ,
					'hash_str' => $part4_9.$checkData['instrument_sn'],
					'hash_32' => md5($part4_9.$checkData['instrument_sn']),
					'hash_16' => substr(md5($part4_9.$checkData['instrument_sn']), 8, 16)
				];
				
				if($logData['ParameterCheck']['Hash']['part12-27'] != $logData['ParameterCheck']['Hash']['hash_16']){
					$checkTag = false;
					$logData['ParameterCheck']['Hash']['error'] = 'Hash Inconformity.';
					break;
				}			
			}	
			break;
			
			case 'SN1001':
			break;

			case 'SN1002':
			break;

			case 'SN1003':
			break;

			case 'SN1004':
				// 必传参数
				$require_parameters = ['token','instrument_sn','check'];
				foreach($require_parameters as $val) {
					$checkData["$val"] = $this->request->get($val) ?: '';					
					if(empty($checkData["$val"])){
						$this->error(__('Missing Parameter'));
					} 
					if($val == 'instrument_sn'){
						$this->doCheckInstrumentSn($checkData["$val"]);
					}
				}				
				
				// token 有效性检查				
				$tokenData = ApiToken::get($checkData["token"]);				
				if(!count($tokenData)){
					$this->error(__('Invalid Token'));
				}
				// 数据合法性检查
				$token5_8 = substr($checkData["token"],4,4);
				$hash = $token5_8.$checkData["instrument_sn"];
				$md5_32 = md5($hash);
				$logData['ParameterCheck']['Hash'] = [
					'token5_8' => $token5_8,
					'hash' => $hash,
					'md5_32' => $md5_32
				];
				
				if($md5_32 != $checkData['check'])
				{
					$checkTag = false;
					$logData['ParameterCheck']['Hash']['error'] = 'Hash Inconformity.';
					break;
				}		
				
			break;

			case 'SN1005':
			break;

			case 'SN1006':
			break;		
		}
		
		// 接口校验参数
		$logData['ParameterCheck']['Params'] = $checkData;
		
		$this->apiResponse[$apiSn] = array(
			'code' => $checkTag,
			'data' => array(
				'check_log' => $logData,
			),
		);
		
		return true;		
		/* $setting = $this->getApiSetting($apiSn);
		var_dump($setting); exit;
		 */
		
	 }
	 
	 // 验证接口调用次数
	 public function doTimesCheck($apiSn, $instrument_sn)
	 {		 
		 
		$setting_times  = 0; // 接口设置次数
		$calling_times	= 0; // 接口调用次数
		
		$apiConf = $this->getApiSetting($apiSn, 'apitimesperday as times'); // 获取配置
		$calling_times = $this->getDayCallingTimes($apiSn, $instrument_sn);  // 获取日常			
		if(count($apiConf)){
			$setting_times = $apiConf['times'];
		}
		
		if($setting_times && $setting_times <= $calling_times ){
			$this->error(__('Times Over'));
		}
		
	 }
	 
	 // 验证接口空间使用量
	 public function doSpaceCheck(){
		 
	 }
	 
	// 获取记录接口调用的次数
	public function getDayCallingTimes($apiSn = null , $instrument_sn = null)
	{
		if(empty($apiSn) || empty($instrument_sn)){
			$this->error(__('Missing Parameter'));
		}
		
		$where = [
			'apisn' => $apiSn,
			'instrument_sn' => $instrument_sn,
			'apiday' => date('Y-m-d')
		];
		
		$row = Db::name('apidaycalling')->where($where)->find();
		
		if(empty($row)){
			return 0;
		} else {
			return $row['apitimes'];
		}		
	}
	
	
	 // 验证仪器序列号是否合法
	 public function doCheckInstrumentSn($instrumentSn = null)
	 {
		$w = ['instumentsno' => $instrumentSn];
		$cn = Db::name('salemanagement')->where($w)->count();
		
		if(!$cn) {
			$this->error(__('Data Error'));
		}		 
	 }
	 
	 // 根据仪器序列号获得所属人: 仪器销售记录表- salemanagement
	 public function getAdminIdByInstrumentSn($instrumentSn = null, $field = '*')
	 {
		 if(is_null($instrumentSn)){
			 return [];
		 }
		 
		 $w = [
			'instumentsno' => $instrumentSn
		 ];
		 $r = Db::name('salemanagement')->field($field)->where($w)->find();
		
		 return $r;
	 }
	 
	 // 记录接口调用日志
	 public function doApiLog($apiSn = null, $instrumentSn = null, $responseCode = '0', $responseData = null)
	 {
		$apiSetting = $this->getApiSetting($apiSn, 'logstate');
			
		// 关闭日志记录的话，直接返回
		if(count($apiSetting) && ! $apiSetting['logstate']){
			return true;
		}
		
		// 获得仪器序列号销售情况
		$r = $this->getAdminIdByInstrumentSn($instrumentSn, "admin_id, instumenttype");		
		$admin_id = 1;
		$instrumenttype = 'no type';
		if(count($r)){
			$admin_id = $r['admin_id'];
			$instrumenttype = $r['instumenttype'];
		}
		
		$request_header = $this->request->header();
		if(is_array($request_header)){
			$request_header = var_export($request_header, true);
		}
		
		$request_data = $this->request->request();
		if(is_array($request_data)){
			$request_data = var_export($request_data, true);
		}
		
		$memo = $this->apiResponse[$apiSn];
		$memo = $memo['data'];
		if(is_array($memo)){
			$memo = var_export($memo, true);
		}
		
		$data = array(
			'admin_id' => $admin_id,
			'instrumenttype' => $instrumenttype,
			'instrumentsno' => $instrumentSn,
			'apisn' => $apiSn,
			'ip' => $this->request->ip(),
			'requesturl' => $this->request->url(),
			'requestheader' => $request_header,
			'requestdata' => $request_data,
			'responsecode' => $responseCode,
			'responsedata' => $responseData,
			'memo' => $memo,
			'createtime' => time()
		);
		
		$r = Db::name('apilog')->insert($data);
		return $r;		 
	 }
	 
}
